package server

import (
	"fmt"
	"gitee.com/it-wind/simple_http"
	"log"
	"net"
	"time"
)

type TcpServer struct {
	*simple_http.Router
	net.Listener
	address string
}

func (s *TcpServer) Run() {
	defer s.Listener.Close()
	for {
		conn, err := s.Listener.Accept()
		if err != nil {
			fmt.Println(err.Error())
			time.Sleep(time.Second)
			continue
		}
		go ProcessClient(conn, s.Router)
	}
}

func NewTcpServer(address string) (s TcpServer) {
	s = TcpServer{
		address: address,
		Router:  simple_http.NewRouter(),
	}

	server, err := net.Listen("tcp", address)
	if err != nil {
		panic(err)
	}
	s.Listener = server
	return
}

func ProcessClient(conn net.Conn, router *simple_http.Router) {
	defer conn.Close()

	for {
		err := simple_http.AcceptRequest(conn, router)
		if err != nil {
			log.Fatalln(err)
		}
	}
}
